//
//  TJUserAcountViewModel.swift
//  WeiBo
//
//  Created by TanJian on 15/12/8.
//  Copyright © 2015年 Joshpell. All rights reserved.
//

import UIKit

class TJUserAcountViewModel {
    
    var userAccount:TJUserAcountModel?
    
    //提供单例供controller调用方法
    static let shareViewModel:TJUserAcountViewModel = TJUserAcountViewModel()
    
    
    //归档与解档的路径
    var filePath:String = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.archive")
    
    private init(){
        
        userAccount = unarchiveForUserInfo()
    }
    
    
    var isExpires : Bool {
        
        guard let expiresDate = userAccount?.expiresDate else {
            return true
        }
        
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {
            return false
        }
        return true
        
    }
    
    var accessToken : String?{
        
        //判断是否过期
        if let accessToken = userAccount?.access_token where !isExpires {

            return accessToken
        }
        return nil
    }
    
    //是否登录
    var isLogon : Bool {
        return accessToken != nil
    }
    
}


extension TJUserAcountViewModel{
    
    
    
    func loadAccessToken(code:String,complete:(isSuccess:Bool) -> ()) {
        
        TJHttpTool.shareTool.loadAccessToken(code) { (response, error) -> () in
            
            if error != nil {
                print("请求错误")
                complete(isSuccess: false)
                return
            }
            
            //判断数据是不是字典
            guard let dict = response as? [String: AnyObject] else{
                print("数据不是字典")
                return
            }
            print(dict)
            let account = TJUserAcountModel(dict: dict)

            self.userAccount = account

            self.loadUserInfo(account.uid!, accessToken: account.access_token!, complete: complete)

            
        }
    }
    
    private func loadUserInfo(uid:String,accessToken:String,complete:(isSuccess:Bool) ->()) {
        
        
        TJHttpTool.shareTool.loadUserInfo(uid,accessToken: accessToken){ (response, error) -> () in
            if error != nil {
                
                print("用户信息请求数据错误")

                complete(isSuccess: false)
                return
            }
            //                print("-----------\(response)")
            //判断数据是否是字典类型，是则储存用户数据
            guard let result = response  as? [String:AnyObject] else{
                print("数据不是字典")
                return
            }
            print(result)
            self.userAccount?.avatar_large = result["avatar_large"] as? String
            self.userAccount?.screen_name = result["screen_name"] as? String
            

            //保存用户数据
            self.saveUserInfo(self.userAccount!)

            complete(isSuccess: true)
            
        }
        
    }

}



//归档与解归档当前对象
extension TJUserAcountViewModel{
    
    func saveUserInfo(account:TJUserAcountModel){
        
         NSKeyedArchiver.archiveRootObject(account, toFile: filePath)
        
    }
    
    
    //解档
    func unarchiveForUserInfo() -> TJUserAcountModel? {
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? TJUserAcountModel
        print(filePath)
        return result
    }
}
    
    
    
    
    
    
    
